package com.ruoyi.map.userController;


import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.index.domain.FhIndexPostinfo;
import com.ruoyi.index.service.IFhIndexPostinfoService;
import com.ruoyi.info.domain.FhInfoFishpoint;
import com.ruoyi.info.service.IFhInfoFishpointService;
import com.ruoyi.map.domain.*;
import com.ruoyi.map.service.*;
import com.ruoyi.tokenTools.UserLoginToken;
import com.test.aop.UserThreadLocal;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 地图模块接口管理Controller
 *
 * @author ruoyi
 * @date 2024-11-12
 */
@Api(tags = "地图模块接口")
@RestController
@RequestMapping("/map/userMap")
public class UserFhMapController extends BaseController {

    @Autowired
    private IFhIndexPostinfoService iFhIndexPostinfoService;


    @Autowired
    private IFhMapFishtypeService fhMapFishtypeService;

    @Autowired
    private IFhMapBaitrecommendService iFhMapBaitrecommendService;

    @Autowired
    private IFhMapFishbaitService fhMapFishbaitService;

    @Autowired
    private IFhInfoFishpointService fhInfoFishpointService;

    @Autowired
    private IFhMapWaterService fhMapWaterService;

    @Autowired
    private IFhMapWatercommonfishService fhMapWatercommonfishService;

    @Autowired
    private IFhMapFishprotectionService fhMapFishprotectionService;

    /**
     * 查询附进渔获
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("附近渔获")
    @GetMapping("/nearbyCatch")
    public R<ArrayList<String>> nearbyCatch(String longitude, String latitude)
    {
        try {
            FhIndexPostinfo fhIndexPostinfo = new FhIndexPostinfo();
            fhIndexPostinfo.setLongitude(longitude);
            fhIndexPostinfo.setLatitude(latitude);
            List<FhIndexPostinfo> fhIndexPostinfoList = iFhIndexPostinfoService.selectFhIndexPostinfoList(fhIndexPostinfo);
            ArrayList<String> nearbyCatchImageList = new ArrayList<>();
            if(fhIndexPostinfoList.isEmpty()){
                return R.ok();
            }
            for (FhIndexPostinfo indexPostinfo : fhIndexPostinfoList) {
                String postImages = indexPostinfo.getPostImages();
                String[] postImageList = postImages.split(",");
                nearbyCatchImageList.addAll(Arrays.asList(postImageList));
            }
            return R.ok(nearbyCatchImageList);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    //定时更新水域常见鱼种表
    @Scheduled(cron ="0 0 0 1/1 * ?")
//    @Scheduled(cron ="0/5 * * * * ?")
    public void timedUpdateWaterCommonFish() {
        FhMapWater fhMapWater = new FhMapWater();
        List<FhMapWater> fhMapWaters = fhMapWaterService.selectFhMapWaterList(fhMapWater);
        //清空水域常见鱼种表
        Long[] waterIdList = new Long[fhMapWaters.size()];
        for (int i = 0; i < fhMapWaters.size(); i++) {
            waterIdList[i] = fhMapWaters.get(i).getId();
        }
        fhMapWatercommonfishService.deleteFhMapWatercommonfishByWaterIds(waterIdList);
        //更新水域常见鱼种表
        for (int i = 0; i < fhMapWaters.size(); i++) {
            FhMapWater fhMapWaterInfo = fhMapWaters.get(i);
            FhIndexPostinfo fhIndexPostinfo = new FhIndexPostinfo();
            fhIndexPostinfo.setLongitude(fhMapWaterInfo.getLongitude());
            fhIndexPostinfo.setLatitude(fhMapWaterInfo.getLatitude());
            List<FhIndexPostinfo> fhIndexPostinfos = iFhIndexPostinfoService.selectFhIndexPostinfoList(fhIndexPostinfo);
            //该水域出现捕获过的鱼种以及次数
            Map<String, Integer> fishIdCatchNum = new HashMap<>();
            for (int j = 0; j < fhIndexPostinfos.size(); j++) {
                FhIndexPostinfo fhIndexPostinfoInfo = fhIndexPostinfos.get(j);
                String[] fishIdList = fhIndexPostinfoInfo.getFishIds().split(",");
                for (String str : fishIdList) {
                    fishIdCatchNum.put(str, fishIdCatchNum.getOrDefault(str, 0) + 1);
                }
            }
            System.out.println(fishIdCatchNum);
            //统计该水域捕获总数，每种渔获种类的数量，更新到数据库
            int waterCatchCount = 0;
            for (Map.Entry<String, Integer> entry : fishIdCatchNum.entrySet()) {
                waterCatchCount+=entry.getValue();
                FhMapWatercommonfish fhMapWatercommonfish = new FhMapWatercommonfish();
                fhMapWatercommonfish.setWaterId(fhMapWaterInfo.getId());
                fhMapWatercommonfish.setWaterName(fhMapWaterInfo.getWaterName());
                fhMapWatercommonfish.setFishId(Long.valueOf(entry.getKey()));
                fhMapWatercommonfish.setCatchNum(Long.valueOf(entry.getValue()));
                FhMapFishtype fhMapFishtype = fhMapFishtypeService.selectFhMapFishtypeById(Long.valueOf(entry.getKey()));
                fhMapWatercommonfish.setFishImage(fhMapFishtype.getFishImage());
                fhMapWatercommonfish.setFishName(fhMapFishtype.getFishType());
                //更新水域常见鱼类表
                fhMapWatercommonfishService.insertFhMapWatercommonfish(fhMapWatercommonfish);
            }
            //更新该水域捕获总数
            fhMapWaterInfo.setCatchTotal(Long.valueOf(waterCatchCount));
            fhMapWaterService.updateFhMapWater(fhMapWaterInfo);
        }

    }

    /**
     * 查询附近水域鱼类
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("附近水域鱼类")
    @GetMapping("/nearbyWaterFish")
    public R<List<NearbyFishType>> nearbyWaterFish(String longitude, String latitude )
    {
//        startPage();
        //返回参数，附近水域鱼种类
        List<NearbyFishType> nearbyFishTypeList = new ArrayList<>();

        //查询附近水域。将附近水域的常见鱼种添加到返回数据中
        FhMapWater fhMapWater = new FhMapWater();
        fhMapWater.setLongitude(longitude);
        fhMapWater.setLatitude(latitude);
        List<FhMapWater> fhMapWaters = fhMapWaterService.selectFhMapWaterList(fhMapWater);
        //附近没有水域
        if(fhMapWaters.isEmpty()){
            return R.ok();
        }
        //附近存在水域
        FhMapWater fhMapWaterInfo = fhMapWaters.get(0);
        Long waterId = fhMapWaterInfo.getId();
        List<FhMapWatercommonfish> fhMapWatercommonfishList = fhMapWatercommonfishService.selectMapWatercommonfishListByWaterId(waterId);
        for (int i = 0; i < fhMapWatercommonfishList.size(); i++) {
            FhMapWatercommonfish fhMapWatercommonfishInfo = fhMapWatercommonfishList.get(i);
            NearbyFishType nearbyFishType = new NearbyFishType();
            nearbyFishType.setFishId(fhMapWatercommonfishInfo.getFishId());
            nearbyFishType.setFishType(fhMapWatercommonfishInfo.getFishName());
            nearbyFishType.setFishImage(fhMapWatercommonfishInfo.getFishImage());
            nearbyFishType.setCatch_num(fhMapWatercommonfishInfo.getCatchNum());
            //查询该鱼种推荐鱼饵列表
            FhMapBaitrecommend fhMapBaitrecommend = new FhMapBaitrecommend();
            fhMapBaitrecommend.setFishId(fhMapWatercommonfishInfo.getFishId());
            List<FhMapBaitrecommend> fhMapBaitrecommends = iFhMapBaitrecommendService.selectFhMapBaitrecommendList(fhMapBaitrecommend);
            nearbyFishType.setFhMapBaitrecommendList(fhMapBaitrecommends);

            nearbyFishTypeList.add(nearbyFishType);
        }

        return R.ok(nearbyFishTypeList);
    }


    /**
     * 查询附近注意事项
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("附近注意事项")
    @GetMapping("/nearbyAttention")
    public R<NearbyAttentionDto> nearbyAttention(String longitude, String latitude)
    {
        try{
            //法律法规模块
            NearbyAttentionDto nearbyAttentionDto = new NearbyAttentionDto();
            nearbyAttentionDto.setLaw("根据相关法律法规，为了保护水产资源和生态环境，对钓鱼行为进行了一定的规范和限制，在禁渔区、禁渔期或者使用禁用的工具、方法捕捞水产品，情节严重的，会受到法律的制裁。");

            //附近禁止钓鱼水域
            FhMapWater fhMapWater = new FhMapWater();
            fhMapWater.setLongitude(longitude);
            fhMapWater.setLatitude(latitude);
            List<FhMapWater> fhMapWaters = fhMapWaterService.selectFhMapWaterList(fhMapWater);
            ArrayList<FhMapWater> fhMapWatersDto = new ArrayList<>();
            for (int i = 0; i < fhMapWaters.size(); i++) {
                if(fhMapWaters.get(i).getUseStatus().equals("1")){
                    fhMapWatersDto.add(fhMapWaters.get(i));
                }
            }
            nearbyAttentionDto.setFhMapWaterList(fhMapWatersDto);

            //附近保护鱼种模块
            ArrayList<FhMapFishprotection> fhMapFishprotections = new ArrayList<>();
            //附近没有水域
            if(fhMapWaters.isEmpty()){
                nearbyAttentionDto.setFhMapFishprotectionList(fhMapFishprotections);
            }else{
                for (int j = 0; j < fhMapWaters.size(); j++) {
                    //附近存在水域
                    FhMapWater fhMapWaterInfo = fhMapWaters.get(j);
                    Long id = fhMapWaterInfo.getId();
                    FhMapWatercommonfish fhMapWatercommonfish = new FhMapWatercommonfish();
                    fhMapWatercommonfish.setWaterId(id);
                    List<FhMapWatercommonfish> fhMapWatercommonfishList = fhMapWatercommonfishService.selectFhMapWatercommonfishList(fhMapWatercommonfish);
                    for (int i = 0; i < fhMapWatercommonfishList.size(); i++) {
                        Long fishId = (long) i;
                        FhMapFishprotection fhMapFishprotection = fhMapFishprotectionService.selectFhMapFishprotectionById(fishId);
                        if (fhMapFishprotection!=null){
                            fhMapFishprotections.add(fhMapFishprotection);
                        }
                    }
                    nearbyAttentionDto.setFhMapFishprotectionList(fhMapFishprotections);
                }
            }

            return R.ok(nearbyAttentionDto);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }

    }


    /**
     * 获取鱼类管理详细信息
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("鱼类详情鱼种百科")
    @GetMapping(value = "/fishtype/{fishId}")
    public R<FhMapFishtype> getFishInfo(@PathVariable("fishId") Long fishId)
    {
        try{
            FhMapFishtype fhMapFishtype = fhMapFishtypeService.selectFhMapFishtypeById(fishId);
            return R.ok(fhMapFishtype);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 获取鱼饵推荐
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("鱼类详情鱼饵推荐")
    @GetMapping("/baitRecommend")
    public R<List<FhMapBaitrecommend>> baitRecommend(Long fishId)
    {
        try {
            FhMapBaitrecommend fhMapBaitrecommend = new FhMapBaitrecommend();
            fhMapBaitrecommend.setFishId(fishId);
            List<FhMapBaitrecommend> fhMapBaitrecommends = iFhMapBaitrecommendService.selectFhMapBaitrecommendList(fhMapBaitrecommend);
            return R.ok(fhMapBaitrecommends);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }

    }

    /**
     * 获取鱼类详情最近渔获
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("鱼类详情最近渔获")
    @GetMapping("/recentCatch")
    public R<List<String>> recentCatch(Long fishId)
    {
        try{
            //返回数据,鱼类最近渔获图片
            List<String> recentCatchList = new ArrayList<>();

            FhIndexPostinfo fhIndexPostinfo = new FhIndexPostinfo();
            List<FhIndexPostinfo> fhIndexPostinfos = iFhIndexPostinfoService.selectFhIndexPostinfoList(fhIndexPostinfo);
            for (int i = 0; i < fhIndexPostinfos.size(); i++) {
                FhIndexPostinfo newFhIndexPostinfo = fhIndexPostinfos.get(i);
                String[] fishIdList = newFhIndexPostinfo.getFishIds().split(",");
                if(fishIdList.length==1){
                    if(Long.valueOf(fishIdList[0])==fishId){
                        recentCatchList.addAll(Arrays.asList(newFhIndexPostinfo.getPostImages().split(",")));
                    }
                }
            }
            return R.ok(recentCatchList);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 获取鱼饵详细信息
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("鱼饵推荐详情")
    @GetMapping(value = "/fishBait/{baitId}")
    public R<FhMapFishbait> getFishBaitInfo(@PathVariable("baitId") Long id)
    {
        try {
            return R.ok(fhMapFishbaitService.selectFhMapFishbaitById(id));
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }


    /**
     * 水域详情
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("水域详情")
    @GetMapping(value = "/water/{waterId}")
    public R<WaterInfoDto> getWaterInfo(@PathVariable("waterId") Long waterId)
    {
        try{
            WaterInfoDto waterInfoDto = new WaterInfoDto();

            //水域详情
            FhMapWater fhMapWater = fhMapWaterService.selectFhMapWaterById(waterId);
            waterInfoDto.setFhMapWater(fhMapWater);

            //常见鱼种
            FhMapWatercommonfish fhMapWatercommonfish = new FhMapWatercommonfish();
            fhMapWatercommonfish.setWaterId(waterId);
            List<FhMapWatercommonfish> fhMapWatercommonfishList = fhMapWatercommonfishService.selectFhMapWatercommonfishList(fhMapWatercommonfish);
            waterInfoDto.setFhMapWatercommonfishList(fhMapWatercommonfishList);

            //最近渔获照片
            List<String> catchImages = new ArrayList<>();
            FhIndexPostinfo fhIndexPostinfo = new FhIndexPostinfo();
            fhIndexPostinfo.setLongitude(fhMapWater.getLongitude());
            fhIndexPostinfo.setLatitude(fhMapWater.getLatitude());
            List<FhIndexPostinfo> fhIndexPostinfos = iFhIndexPostinfoService.selectFhIndexPostinfoList(fhIndexPostinfo);
            for (int i = 0; i < fhIndexPostinfos.size(); i++) {
                String[] fhIndexPostimages = fhIndexPostinfos.get(i).getPostImages().split(",");
                if(fhIndexPostimages.length == 0){
                    continue;
                }
                catchImages.addAll(Arrays.asList(fhIndexPostimages));
            }
            waterInfoDto.setCatchImageList(catchImages);

            return R.ok(waterInfoDto);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }

    }


    /**
     * 搜素水域
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("搜素水域")
    @GetMapping ("/searchWater")
    public R<List<FhMapWater>> searchWater(String waterName)
    {
        try{
            FhMapWater fhMapWater = new FhMapWater();
            fhMapWater.setWaterName(waterName);
            List<FhMapWater> fhMapWaters = fhMapWaterService.selectFhMapWaterList(fhMapWater);
            return R.ok(fhMapWaters);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }


    /**
     * 附近水域
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("附近水域")
    @GetMapping("/nearyWater")
    public R<List<FhMapWater>> nearbyWater(String longitude, String latitude)
    {
        try{
            FhMapWater fhMapWater = new FhMapWater();
            fhMapWater.setLongitude(longitude);
            fhMapWater.setLatitude(latitude);
            List<FhMapWater> fhMapWaters = fhMapWaterService.selectFhMapWaterList(fhMapWater);
            return R.ok(fhMapWaters);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 筛选渔获
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("筛选渔获")
    @PostMapping("/screeningCatch")
    public R<List<FhIndexPostinfo>> screeningCatch(ScreeningCatchDto screeningCatchDto)
    {
        try {
            List<FhIndexPostinfo> fhIndexPostinfoList = iFhIndexPostinfoService.screeningCatchList(screeningCatchDto);
            return R.ok(fhIndexPostinfoList);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }


    /**
     * 新增钓鱼点管理
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("添加钓鱼点")
    @PostMapping("/AddFishPoint")
    public R<String> add(FhInfoFishpoint fhInfoFishpoint)
    {
        try {
            fhInfoFishpointService.insertFhInfoFishpoint(fhInfoFishpoint);
            return R.ok("添加成功");
        }catch (Exception e){
            return R.fail();
        }
    }


    /**
     * 查询钓鱼点列表
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("查询用户钓鱼点列表")
    @GetMapping("/userFishPointlist")
    public R<List<FhInfoFishpoint>> list()
    {
        try{
            startPage();
            Long userId = UserThreadLocal.getUser();
            FhInfoFishpoint fhInfoFishpoint = new FhInfoFishpoint();
            fhInfoFishpoint.setUserId(userId);
            List<FhInfoFishpoint> list = fhInfoFishpointService.selectFhInfoFishpointList(fhInfoFishpoint);
            return R.ok(list);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }


}
